package com.demo.spring.aop底层演示.demo3;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MyInvocation implements MethodInvocation {
	
	// 被代理的类
	private Object target;
	// 被代理的方法
	private Method method;
	// 被代理方法的参数
	private Object[] args;
	// 环绕通知集合
	private List<MethodInterceptor> methodInterceptorList;
	// 调用次数
	private int count = 1;

	public MyInvocation(Object target, Method method, Object[] args, List<MethodInterceptor> methodInterceptorList) {
		super();
		this.target = target;
		this.method = method;
		this.args = args;
		this.methodInterceptorList = methodInterceptorList;
	}

	@Override
	public Object[] getArguments() {
		return args;
	}

	@Override
	// 调用每一个环绕通知，最后调用目标
	public Object proceed() throws Throwable {
		// 递归调用就在这里，总共调用methodInterceptorList.size + target本身1次
		if(count > methodInterceptorList.size()) {
			// 调用目标，返回并结束递归
			return method.invoke(target, args);
		}
		// 逐一调用通知，并count+1
		MethodInterceptor methodInterceptor = methodInterceptorList.get(count++ - 1);
		return methodInterceptor.invoke(this);
	}

	@Override
	public Object getThis() {
		return target;
	}

	@Override
	public AccessibleObject getStaticPart() {
		return method;
	}

	@Override
	public Method getMethod() {
		return method;
	}

}
